package com.zl;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class ClientHandler extends
        SimpleChannelInboundHandler<DatagramPacket> {

    int i = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
            throws Exception {
        //获得应答，DatagramPacket提供了content()方法取得报文的实际内容
        String response = msg.content().toString(CharsetUtil.UTF_8);
        if (response.startsWith(UdpServer.ANSWER)) {
            System.out.println(response);
        }
        System.out.println(i);
        Thread.sleep(3000);
        ctx.writeAndFlush( new DatagramPacket(
                Unpooled.copiedBuffer(
                       String.valueOf(++i),
                        CharsetUtil.UTF_8),
//可以看请求端此处new InetSocketAddress("127.0.0.1",port)，而应答端可以直接从packet.sender())中获取这个属性，所以不用重新new了
                msg.sender()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}